package com.bing.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * Created by kaibb on 15-11-25.
 */
public class PingTool {
    private static final Logger LOGGER = LoggerFactory.getLogger(PingTool.class);
    private static final int TIMEOUT = 5000;

    private static ThreadLocal<Socket> socketThreadLocal = new ThreadLocal<>();

    public static boolean ping(InetSocketAddress address) {
        boolean flag = false;
        Socket socket = getSocket();
        try {
            socket.connect(address, TIMEOUT);
            LOGGER.info("连接成功:{}", address);
            flag = true;
        } catch (IOException e) {
            LOGGER.debug("连接异常{}", address.toString());
        }
        return flag;
    }

    public static boolean ping(String host, int port) {
        return ping(new InetSocketAddress(host, port));
    }

    private static Socket getSocket() {
        Socket socket = socketThreadLocal.get();
        if (socket == null) {
            LOGGER.info("初始化socket for:{}", Thread.currentThread().getName());
            socket = new Socket();
            socketThreadLocal.set(socket);
        }
        return socket;
    }
}
